import {HTTP} from "../../../utils/http.js"
import {UserModel} from "../../../models/user.js";
const User = new UserModel();
const app = getApp();
var http = new HTTP();
var _self;
Page({
  data: {
    birthDate:"1985-05-05",
    region: [],
    wechatid:"",
    userName:"",
    sexArr:['女', '男'],
    sexIndex: 0,
    customItem: '全部',
    wxysArr:['所有人可见','好友可见','自己可见'],
    deftWxysIndex:0,
    phoneArr: ['公开', '好友可见', '保密'],
    deftPhoneIndex:0
  },
  onLoad: function (options) {
    _self = this;
    _self.fetchPersonalInfo()
  },
  fetchPersonalInfo:function(){

    User.fetch(function (userInfo) {
      app.globalData.personalInfo = userInfo;
      _self.initPersonalData(userInfo);
    })
  },
  initPersonalData:function(userInfo){
      let region = userInfo.address.split(',');
      let sexIndex= userInfo.sex=="女"?0:1;
      _self.setData({
        userName: userInfo.userName,
        region: region,
        birthDate: userInfo.user.birthday,
        // wechatid: userInfo.user.wechatid,
        sexIndex: sexIndex,
        // deftWxysIndex: userInfo.user.isshowwechat,
        deftPhoneIndex: userInfo.user.isshowmobile
      });
  },
  bindRegionChange:function(e){
    this.setData({
      region: e.detail.value
    })
  }
  ,
  bindDateChange:function(e){
    this.setData({
      birthDate: e.detail.value
    })
  },
  sexChange: function (e) {
    this.setData({
      sexIndex: e.detail.value
    })
  },
  wxysChange:function(e){
    this.setData({
      deftWxysIndex: e.detail.value
    })
  },
  phoneChange: function (e) {
    this.setData({
      deftPhoneIndex: e.detail.value
    })
  },
  formSubmit:function(e){
    let data = {
      // "userName":e.detail.value.userName,
      "sex":this.data.sexArr[this.data.sexIndex],
      "birthday":this.data.birthDate,
      "address": this.data.region.join(','),
      "isshowmobile":this.data.deftPhoneIndex+""
      //"wechatid":e.detail.value.wechatid+"",
      //"isshowwechat":this.data.deftWxysIndex+""  
    }
    this.updateInfo(data);
  },
  updateInfo:function(data){
    http.request({
      url: "/usr/updatePersonInf",
      data: data,
      method: "POST",
      success: function (data) {
              User.fetch(function (userInfo) {
                app.globalData.personalInfo = userInfo;
                _self.initPersonalData(userInfo);

                var pages = getCurrentPages();
                if (pages.length > 1) {
                  var prePage = pages[pages.length - 2];
                  prePage.changeData("userInfoChanged");
                  wx.navigateBack();
                }
                return;
              })      
      }
    })
  },
  logout: function () {
    http.request({
      url: "/usr/logout",
      method: "POST",
      success: function (data) {
        wx.redirectTo({
          url: "/pages/login/login"
        })
      }
    })
  }
})